package com.yeqifu.bus.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeqifu.bus.echarts.SaleShop;
import com.yeqifu.bus.entity.Customer;
import com.yeqifu.bus.entity.Goods;
import com.yeqifu.bus.entity.Sales;
import com.yeqifu.bus.service.ICustomerService;
import com.yeqifu.bus.service.IGoodsService;
import com.yeqifu.bus.service.ISalesService;
import com.yeqifu.bus.vo.SalesVo;
import com.yeqifu.sys.common.*;
import com.yeqifu.sys.entity.User;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 * InnoDB free: 9216 kB 前端控制器
 * </p>
 *
 * @author luoyi-
 * @since 2019-12-21
 */
@RestController
@RequestMapping("/sales")
public class SalesController {

    @Autowired
    private ISalesService salesService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private IGoodsService goodsService;

    /**
     * 查询所有商品销售信息
     * @param salesVo
     * @return
     */
    @RequestMapping("loadAllSales")
    public DataGridView loadAllSales(SalesVo salesVo){
        IPage<Sales> page = new Page<>(salesVo.getPage(),salesVo.getLimit());
        QueryWrapper<Sales> queryWrapper = new QueryWrapper<Sales>();
        //根据客户进行模糊查询
        queryWrapper.eq(salesVo.getCustomerid()!=null&&salesVo.getCustomerid()!=0,"customerid",salesVo.getCustomerid());
        //根据商品模糊查询
        queryWrapper.eq(salesVo.getGoodsid()!=null&&salesVo.getGoodsid()!=0,"goodsid",salesVo.getGoodsid());
        //根据时间进行模糊查询
        queryWrapper.ge(salesVo.getStartTime()!=null,"salestime",salesVo.getStartTime());
        queryWrapper.le(salesVo.getEndTime()!=null,"salestime",salesVo.getEndTime());
        IPage<Sales> page1 = salesService.page(page, queryWrapper);
        List<Sales> records = page1.getRecords();
        for (Sales sales : records) {
            //设置客户姓名
            Customer customer = customerService.getById(sales.getCustomerid());
            if(null!=customer){
                sales.setCustomername(customer.getCustomername());
                sales.setPhone(customer.getCustomername());
            }
            //设置商品名称
            Goods goods = goodsService.getById(sales.getGoodsid());
            if (null!=goods){
                //设置商品名称
                sales.setGoodsname(goods.getGoodsname());
                //设置商品规格
                sales.setSize(goods.getSize());
                //设置商品总价
                sales.setSum(sales.getNumber() *sales.getSaleprice());
            }
        }
        return new DataGridView(page1.getTotal(),page1.getRecords());
    }

    /**
     * 添加商品销售信息
     * @param salesVo
     * @return
     */
    @RequestMapping("addSales")
    public ResultObj addSales(SalesVo salesVo){
        try {
            //获得当前系统用户
            User user = (User) WebUtils.getSession().getAttribute("user");
            //设置操作人
            salesVo.setOperateperson(user.getName());
            //设置销售时间
            salesVo.setSalestime(new Date());
            salesService.save(salesVo);
            return ResultObj.ADD_SUCCESS;
        }catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 更新商品销售信息
     * @param salesVo
     * @return
     */
    @RequestMapping("updateSales")
    public ResultObj updateSales(SalesVo salesVo){
        try {
            salesService.updateById(salesVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 删除商品销售信息
     * @param id
     * @return
     */
    @RequestMapping("deleteSales")
    public ResultObj deleteSales(Integer id){
        try {
            salesService.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 确定购物消息
     * @param id
     * @return
     */

    @RequestMapping("/confirm")
    public ResultObj confirm(Integer id){
        try {
            salesService.updateNumberAndStatus(id,null,"已送达");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendEmail(id);
                }
            }).start();
            return ResultObj.CONFIRM_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.CONFIRM_ERROR;
        }

    }

    /**
     *
     * @param  id 查询sale
     */
    private void sendEmail(Integer id){
        Sales sales = salesService.getById(id);
        Goods goods = goodsService.getById(sales.getGoodsid());
        Customer customer = customerService.getById(sales.getCustomerid());
        List<Sales> salesList = salesService.selectAllSendCustomer(sales.getCustomerid());
        List<String> fixed = fixed(salesList);
        Set<String> predictType = PredictUtils.getPredictType(goods.getGoodsname());
        String result = "恭喜你本次交易成功，该系统推荐：";
        if(predictType.size() == 0){
            //取最大的两个成交订单
            List<SaleShop> list = salesService.selectMaxThreeShop();
            if(goods.getGoodsname().equals(list.get(0))){
                result += list.get(1).getGoodsName() + "，该商品最近的销量不错，您是否考虑购买？";
            }else {
                result += list.get(0).getGoodsName() + "，该商品的销量是我公司最好的，您是否考虑购买？";
            }
        }else{
            String temp = "";
            for (String s : predictType) {
                temp += s+"；";
            }
            //去除最后的；
            temp = temp.substring(0,temp.length()-1);
            result += temp + "商品智能推荐，其他客户在购买您购买的"+goods.getGoodsname()+"商品后的同时也会购买，您是否也需要购买"+temp+"？";
        }
        MailUtils.sendMail(customer.getEmail(),result,"【商务管理系统】交易完成消息");
        MailUtils.sendMail("1499255046@qq.com",result,"【商务管理系统】交易完成消息");
    }


    /**
     * 封装sale数据
     * @param list
     * @return
     */
    public List<String> fixed(List<Sales> list){
        System.out.println("开始整合初始列表");
        HashMap<Integer, Set<String>> map = new HashMap<>();
        List<String> strings = new ArrayList<>();
        for (Sales sales : list) {
            Set<String> back = map.get(sales.getCustomerid());
            if(back == null || back.isEmpty()){
                //back为空新建
                back = new HashSet<>();
                back.add(sales.getGoodsname());
                map.put(sales.getCustomerid(),back);
            }else {
                back.add(sales.getGoodsname());
                map.put(sales.getCustomerid(),back);
            }

        }
        Set<Integer> set  = map.keySet();
        for (Integer key : set) {
            Set<String> list1 = map.get(key);
            StringBuffer stringBuffer = new StringBuffer();
            for (String s : list1) {
                stringBuffer.append(s+";");
            }
            strings.add(stringBuffer.toString());
        }
        return strings;
    }
}

